---
title: "Step5: Rebranding analysis"
author: "Endre Borbáth and Swen Hutter"
output: html_document
---

# Loading packages

```{r, echo=T, message = T, include = T}

library(readxl)
library(tidyr)
library(dplyr)
library(lubridate)
library(ggplot2)
library(grid)
library(haven)
library(forcats)
library(lmtest)
library(plm)
library(texreg)
library(lme4)
library(broom.mixed)
library(performance)
library(kableExtra)
library(thematic)
library(effects)
library(fixest)
library(parameters)
library(margins)
library(here)
library(tidytext)

rm(list = ls()) 

load("dataset_long.Rdata")

range01 <- function(x){(x-min(x, na.rm = TRUE))/(max(x, na.rm = TRUE)-min(x, na.rm = TRUE))}

colors <- thematic::okabe_ito(8)[-6]

# to calculate margins with 90 and 95 percent CIs
margins_2ci <- function(mod) { 

mar <- margins(mod, type="response")

plot_dat <- summary(mar, level = 0.95) %>% 
  rename(`2.5 %` = lower, 
         `97.5 %` = upper) 

plot_dat2 <- summary(mar, level = 0.90) %>% 
  select(lower, upper) %>% 
  rename(`5 %` = lower,
         `95 %` = upper)

plot_dat <- bind_cols(plot_dat, plot_dat2)
  
plot_dat$model <- as.character(deparse(substitute(mod)))

return(plot_dat)

}


```

# Appendix B

```{r, echo=T, message = T, include = T}

d_lng <- d_lng %>% 
  mutate(ideol_brand = case_when(grepl("Nonideolog", typology) ~ 1,
                                 TRUE ~ 0)) %>% 
  mutate(org_brand = case_when(grepl(" party", typology) ~ "party",
                               grepl("movement", typology) ~ "movement",
                               grepl("nonparty", typology) ~ "nonparty")) %>% 
  mutate(ideological_party = case_when(typology == "Ideological party" ~ 1,
                           typology != "Ideological party" ~ 0)) %>% 
  mutate(nonideological_nonparty = case_when(typology == "Nonideological nonparty" ~ 1,
                           typology != "Nonideological nonparty" ~ 0)) %>% 
  mutate(nonideological_movement = case_when(typology == "Nonideological movement" ~ 1,
                                  typology != "Nonideological movement" ~ 0)) %>% 
  group_by(country, party_id) %>% 
  mutate(n_indic = n_distinct(typology, na.rm = TRUE),
    rb_typology = if_else(n_indic == 1, paste("Consistently", first(typology)), "Changed")) %>% 
  mutate(n_indic = n_distinct(ideol_brand, na.rm = TRUE),
    rb_ideol_brand = if_else(n_indic == 1, paste("Consistently", first(ideol_brand)), "Changed")) %>% 
  mutate(n_indic = n_distinct(org_brand, na.rm = TRUE),
    rb_org_brand = if_else(n_indic == 1, paste("Consistently", first(org_brand)), "Changed")) %>% 
  mutate(n_indic = n_distinct(ideological_party, na.rm = TRUE),
    rb_ideological_party = if_else(n_indic == 1, paste("Consistently", first(ideological_party)), "Changed")) %>% 
  mutate(n_indic = n_distinct(nonideological_nonparty, na.rm = TRUE),
    rb_nonideological_nonparty = if_else(n_indic == 1, paste("Consistently", first(nonideological_nonparty)), "Changed")) %>% 
  mutate(n_indic = n_distinct(nonideological_movement, na.rm = TRUE),
    rb_nonideological_movement = if_else(n_indic == 1, paste("Consistently", first(nonideological_movement)), "Changed")) %>% 
  ungroup(.) %>% 
    mutate_at(vars(starts_with("rb_")), ~ifelse(.=="Changed", 1, 0)) %>% 
  mutate(party_fam = case_when(family_name %in% c("to be coded", 
                                                  "Special issue", 
                                                  "no family") ~ "Other",
                               TRUE ~ family_name),
         opp_party_lag1 = case_when(cabinet_party_lag1 == 0 ~ 1,
                                    cabinet_party_lag1 == 1 ~ 0),
         party_age = log(party_age), # take the log before the centering
         gtm_parl_lag1 = factor(gtm_parl_lag1, levels=c(0, 1)),
         country_year=paste(country, year, sep="_")) %>% 
  mutate(decades=case_when(year<1970 ~ "1945-1969",
                           year>=1970 & year<1990 ~ "1970-1989",
                           year>=1990 & year<2009 ~ "1990-2008",
                           year>=2009 & year<=2023 ~ "2009-2023")) %>% 
  mutate(decades=factor(decades, levels = c("1945-1969", "1970-1989",
                                            "1990-2008", "2009-2023"))) %>% 
  mutate(party_fam=factor(party_fam, levels=c("Christian democracy",  
                                              "Liberal", 
                                              "Social democracy",
                                              "Communist/Socialist", 
                                              "Green/Ecologist", 
                                              "Conservative", 
                                              "Right-wing",
                                              "Agrarian",
                                              "Other"))) %>% 
  mutate(country_decades=paste0(country, "_", as.character(decades))) %>% 
  mutate_at(vars(coalition, opp_party_lag1), ~ factor(., levels = c("0", "1"))) 

```


## Figure 2: Distribution over time of re-branding parties across 28 European countries (1945-2023)


```{r, echo=T, message = T, include = T}

# Define the function
calculate_dummy_share <- function(data, dummy_var) {
  
  # Capture the dummy variable as a quosure
  dummy_var <- enquo(dummy_var)
  
  data %>%
    select(year, !!dummy_var) %>%          # select year and the dummy variable
    group_by(year) %>%
    mutate(total_parties = n()) %>%         # count total parties per year
    ungroup() %>%
    group_by(year, !!dummy_var) %>%
    mutate(nr_parties = n()) %>%            # count parties per year for each dummy value
    ungroup() %>%
    select(year, !!dummy_var, total_parties, nr_parties) %>%
    distinct() %>%                          # remove duplicate rows
    filter(!!dummy_var == 1) %>%            # keep only rows where the dummy is 1
    mutate(share = nr_parties * 100 / total_parties) %>%  # calculate the share
    select(year, share)
}


dat_plot1 <- calculate_dummy_share(d_lng, rb_typology) %>% 
  rename(rb_typology=share)

dat_plot2 <- calculate_dummy_share(d_lng, rb_ideol_brand) %>% 
  rename(rb_ideol_brand=share)

dat_plot3 <- calculate_dummy_share(d_lng, rb_org_brand) %>% 
  rename(rb_org_brand=share)

dat_plot4 <- calculate_dummy_share(d_lng, rb_ideological_party) %>% 
  rename(rb_ideological_party=share)

dat_plot5 <- calculate_dummy_share(d_lng, rb_nonideological_nonparty) %>% 
  rename(rb_nonideological_nonparty=share)

dat_plot6 <- calculate_dummy_share(d_lng, nonideological_movement) %>% 
  rename(rb_nonideological_movement=share)

full_grid <- as.data.frame(expand.grid(year=seq(1945,2023,1)))
full_grid$year <- as.numeric(full_grid$year)


dat_plot <- full_grid %>%
  left_join(dat_plot1, by = "year") %>%
  left_join(dat_plot2, by = "year") %>%
  left_join(dat_plot3, by = "year") %>%
  left_join(dat_plot4, by = "year") %>%
  left_join(dat_plot5, by = "year") %>%
  left_join(dat_plot6, by = "year") %>% 
  pivot_longer(cols = c(rb_typology, rb_ideol_brand, rb_org_brand, 
                        rb_ideological_party, rb_nonideological_nonparty, 
                        rb_nonideological_movement), 
               names_to = "typology", values_to = "share_parties") %>% 
  mutate(share_parties=ifelse(is.na(share_parties), 0, share_parties)) %>% 
  mutate(broad_types=ifelse(typology %in% c("rb_typology", "rb_ideol_brand", 
                                            "rb_org_brand"), "Overall rebranding, in terms of:",
                            "Rebranding into specific types:")) %>% 
  mutate(broad_types=factor(broad_types, levels=c("Overall rebranding, in terms of:", 
                                                  "Rebranding into specific types:"))) %>% 
  mutate(typology=case_when(typology=="rb_typology" ~ "Typology",
                            typology=="rb_ideol_brand" ~ "Ideological dimension",
                            typology=="rb_org_brand" ~ "Organizational dimension",
                            typology=="rb_ideological_party" ~ "Classical party name",
                            typology=="rb_nonideological_nonparty" ~ "Nonideological nonparty name",
                            typology=="rb_nonideological_movement" ~ "Nonideological movement name")) %>% 
  mutate(typology=factor(typology, levels = c("Typology", 
                                              "Ideological dimension", 
                                              "Organizational dimension",
                                              "Classical party name",
                                              "Nonideological nonparty name",
                                              "Nonideological movement name")))


timeline <- ggplot(dat_plot, aes(x=year, y = share_parties, linetype=typology, color=typology)) + 
  geom_line(size=0.75) +
  ylab("Proportion from all names") +
  facet_grid(~broad_types) +
  scale_x_discrete(limits=(seq(1945, 2023, 10))) +
  scale_color_manual(values=c("#0072B2", "#D55E00", "#009E73", "#CCBB44", "#CC79A7",  "#56B4E9")) +
  scale_linetype_manual(values=c("solid", "dotdash", "longdash", "solid", "twodash", "dashed")) +
  guides(color = guide_legend(nrow =3),
         linetype = guide_legend(nrow=3)) +
  theme_bw() + 
  expand_limits(y = 0) +
  theme(
    legend.title = element_blank(), 
    legend.position = "bottom",
    legend.margin = margin(),
    axis.title.x = element_blank(),
    legend.key.width = unit(2, "cm")
  )
        
timeline

ggsave(plot=last_plot(),
      filename = "appendix/figures/re_branding_timeline.eps",
      scale = 2.5,
      width = 6, height = 4, dpi=400, units="cm")


```


```{r, echo=T, message = T, include = T}

reg_dat <- d_lng %>% 
  mutate(coalition=as.numeric(coalition)-1) %>% 
  mutate(ideol_brand = case_when(grepl("Nonideolog", typology) ~ 1,
                                 TRUE ~ 0)) %>% 
  mutate(org_brand = case_when(grepl(" party", typology) ~ "party",
                               grepl("movement", typology) ~ "movement",
                               grepl("nonparty", typology) ~ "nonparty")) %>% 
  mutate(ideological_party = case_when(typology == "Ideological party" ~ 1,
                           typology != "Ideological party" ~ 0)) %>% 
  mutate(nonideological_nonparty = case_when(typology == "Nonideological nonparty" ~ 1,
                           typology != "Nonideological nonparty" ~ 0)) %>% 
  mutate(nonideological_movement = case_when(typology == "Nonideological movement" ~ 1,
                                  typology != "Nonideological movement" ~ 0)) %>% 
  group_by(country, party_id) %>% 
  mutate(n_indic = n_distinct(typology, na.rm = TRUE),
    rb_typology = if_else(n_indic == 1, paste("Consistently", first(typology)), "Changed")) %>% 
  mutate(n_indic = n_distinct(ideol_brand, na.rm = TRUE),
    rb_ideol_brand = if_else(n_indic == 1, paste("Consistently", first(ideol_brand)), "Changed")) %>% 
  mutate(n_indic = n_distinct(org_brand, na.rm = TRUE),
    rb_org_brand = if_else(n_indic == 1, paste("Consistently", first(org_brand)), "Changed")) %>% 
  mutate(n_indic = n_distinct(ideological_party, na.rm = TRUE),
    rb_ideological_party = if_else(n_indic == 1, paste("Consistently", first(ideological_party)), "Changed")) %>% 
  mutate(n_indic = n_distinct(nonideological_nonparty, na.rm = TRUE),
    rb_nonideological_nonparty = if_else(n_indic == 1, paste("Consistently", first(nonideological_nonparty)), "Changed")) %>% 
  mutate(n_indic = n_distinct(nonideological_movement, na.rm = TRUE),
    rb_nonideological_movement = if_else(n_indic == 1, paste("Consistently", first(nonideological_movement)), "Changed")) %>% 
  ungroup(.) %>% 
  mutate_at(vars(starts_with("rb_")), ~ifelse(.=="Changed", 1, 0)) %>% 
  mutate(past_pm=ifelse(past_pm=="has been/is pm party", 1, 0)) %>% 
  group_by(party_id) %>% 
  mutate(nr_year=n_distinct(year, na.rm=TRUE)) %>% 
  mutate(past_pm=sum(past_pm)*100/nr_year) %>%
  mutate(vote_share=mean(vote_share, na.rm=TRUE)) %>%
  mutate(party_age=mean(party_age, na.rm=TRUE)) %>%
  mutate(cmp_econ_polar=mean(cmp_econ_polar, na.rm=TRUE)) %>%
  mutate(cmp_cult_polar=mean(cmp_cult_polar, na.rm=TRUE)) %>%
  mutate(Voter_Turnout=mean(Voter_Turnout, na.rm=TRUE)) %>%
  mutate(tv_it=mean(tv_it, na.rm=TRUE)) %>%
  mutate(v2x_polyarchy=mean(v2x_polyarchy, na.rm=TRUE)) %>%
  mutate(gtm_parl=mean(as.numeric(gtm_parl)-1, na.rm=TRUE)) %>%
  mutate(coalition=sum(coalition)*100/nr_year) %>%
  mutate(estab_year=min(year, na.rm=TRUE)) %>% 
  ungroup() %>% 
  mutate(decades=case_when(estab_year<1970 ~ "1945-1969",
                           estab_year>=1970 & estab_year<1990 ~ "1970-1989",
                           estab_year>=1990 & estab_year<2009 ~ "1990-2008",
                           estab_year>=2009 & estab_year<=2023 ~ "2009-2023")) %>% 
  mutate(decades=factor(decades, levels = c("1945-1969", "1970-1989",
                                            "1990-2008", "2009-2023"))) %>% 
  mutate(party_fam = case_when(family_name %in% c("to be coded", 
                                                  "Special issue", 
                                                  "no family") ~ "Other",
                               TRUE ~ family_name)) %>% 
  mutate(party_fam=factor(party_fam, levels=c("Christian democracy",  
                                              "Liberal", 
                                              "Social democracy",
                                              "Communist/Socialist", 
                                              "Green/Ecologist", 
                                              "Conservative", 
                                              "Right-wing",
                                              "Agrarian",
                                              "Other"))) %>% 
  select(c(starts_with("rb_"), party_id, country, 
              party_fam, past_pm, vote_share, party_age, cmp_econ_polar,
              cmp_cult_polar, Voter_Turnout, tv_it, v2x_polyarchy, gtm_parl, 
              coalition, decades)) %>% 
  unique(.) 

```

## Figure 3: Distribution over party families of re-branding parties across 28 European countries (1945-2023)

```{r, echo=T, message = T, include = T}

calculate_indicator_share <- function(data, indic, DV_label) {
  
  indic <- enquo(indic)
  
  data %>% 
    group_by(party_id, party_fam) %>% 
    mutate(nr_parties = sum(!!indic, na.rm = TRUE)) %>% 
    select(party_fam, nr_parties, party_id, !!indic) %>% 
    distinct() %>% 
    ungroup() %>% 
    # Reset the indicator for each party: if a party has at least one 1, recode it as 1.
    mutate(!!quo_name(indic) := ifelse(nr_parties > 0, 1, 0)) %>% 
    group_by(party_fam) %>% 
    mutate(total = n()) %>% 
    # Sum the (possibly recoded) indicator within family_name
    mutate(!!quo_name(indic) := sum(!!indic)) %>% 
    ungroup() %>% 
    select(party_fam, total, !!indic) %>% 
    distinct() %>% 
    mutate(share = (!!indic) / total * 100) %>% 
    select(-!!indic, -total)
}

dat_plot1 <- calculate_indicator_share(reg_dat, rb_typology) %>% 
  arrange(share) %>% 
  mutate(ranking1=row_number()) %>% 
  rename(rb_typology=share)

dat_plot2 <- calculate_indicator_share(reg_dat, rb_ideol_brand) %>% 
  rename(rb_ideol_brand=share)

dat_plot3 <- calculate_indicator_share(reg_dat, rb_org_brand) %>% 
  rename(rb_org_brand=share)

dat_plot4 <- calculate_indicator_share(reg_dat, rb_ideological_party) %>% 
  arrange(share) %>% 
  mutate(ranking2=row_number()) %>% 
  rename(rb_ideological_party=share)

dat_plot5 <- calculate_indicator_share(reg_dat, rb_nonideological_nonparty) %>% 
  rename(rb_nonideological_nonparty=share)

dat_plot6 <- calculate_indicator_share(reg_dat, rb_nonideological_movement) %>% 
  rename(rb_nonideological_movement=share)

full_grid <- as.data.frame(expand.grid(party_fam=unique(d_lng$party_fam)))

dat_plot <- full_grid %>%
  left_join(dat_plot1, by = "party_fam") %>%
  left_join(dat_plot2, by = "party_fam") %>%
  left_join(dat_plot3, by = "party_fam") %>%
  left_join(dat_plot4, by = "party_fam") %>%
  left_join(dat_plot5, by = "party_fam") %>%
  left_join(dat_plot6, by = "party_fam") %>% 
  pivot_longer(cols = c(rb_typology, rb_ideol_brand, rb_org_brand, 
                        rb_ideological_party, rb_nonideological_nonparty, 
                        rb_nonideological_movement), 
               names_to = "typology", values_to = "share_parties") %>% 
  mutate(share_parties=ifelse(is.na(share_parties), 0, share_parties)) %>% 
  mutate(broad_types=ifelse(typology %in% c("rb_typology", "rb_ideol_brand", 
                                            "rb_org_brand"), "Overall",
                            "Specific types")) %>% 
  mutate(broad_types=factor(broad_types, levels=c("Overall", "Specific types"))) %>% 
  mutate(typology=case_when(typology=="rb_typology" ~ "Typology rebrand",
                            typology=="rb_ideol_brand" ~ "Ideological rebrand",
                            typology=="rb_org_brand" ~ "Organizational rebrand",
                            typology=="rb_ideological_party" ~ "Ideological party rebrand",
                            typology=="rb_nonideological_nonparty" ~ "Nonideological nonparty rebrand",
                            typology=="rb_nonideological_movement" ~ 
                              "Nonideological movement rebrand")) %>% 
  mutate(typology=factor(typology, levels = c("Typology rebrand", 
                                              "Ideological rebrand", 
                                              "Organizational rebrand",
                                              "Ideological party rebrand",
                                              "Nonideological nonparty rebrand",
                                              "Nonideological movement rebrand"))) %>% 
  filter(!(party_fam %in% c("to be coded", "Special issue", "no family", "Other"))) %>% 
  mutate(party_fam=factor(party_fam, levels=c("Communist/Socialist", "Social democracy",
                                                  "Green/Ecologist", "Christian democracy", "Liberal",
                                                  "Conservative", "Agrarian", "Right-wing"))) %>% 
  mutate(party_fam=fct_rev(party_fam)) 

dat_plot1 <- dat_plot %>% 
  filter(broad_types=="Overall") 
  # mutate(party_fam=fct_reorder(party_fam, ranking1))

dat_plot2 <- dat_plot %>% 
  filter(broad_types!="Overall") 
  # mutate(party_fam=fct_reorder(party_fam, ranking2))


overall_plot <- ggplot(dat_plot1, 
       aes(y = party_fam, x=share_parties)) + 
  geom_col(color="black", show.legend = FALSE) + 
  facet_grid(broad_types~typology) +
  scale_y_reordered() +
  xlab("Proportion of parties (pp. within party family)") +
  theme_linedraw() +
  coord_cartesian(xlim=c(0, 37)) +
  guides(fill=guide_legend(nrow=1,byrow=TRUE, reverse = TRUE)) +
  theme(legend.title=element_blank(), 
        legend.position="none",
        axis.title.y=element_blank(),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

bytype_plot <- ggplot(dat_plot2, 
       aes(y = party_fam, x=share_parties)) + 
  geom_col(color="black", show.legend = FALSE) + 
  facet_grid(broad_types~typology) +
  scale_y_reordered() +
  xlab("Proportion of parties (pp. within party family)") +
  theme_linedraw() +
  coord_cartesian(xlim=c(0, 37)) +
  guides(fill=guide_legend(nrow=1,byrow=TRUE, reverse = TRUE)) +
  theme(legend.title=element_blank(), 
        legend.position="none",
        axis.title.y=element_blank())

cowplot::plot_grid(overall_plot, bytype_plot, ncol=1)

ggsave(plot=last_plot(),
      filename = "appendix/figures/re_branding_families.eps",
      scale = 3,
      width = 7, height = 5, dpi=400, units="cm")

```

```{r, echo=T, message = T, include = T}


m.full.1 <- glmer(rb_typology ~
                    party_fam + past_pm + 
                    vote_share + party_age + 1 + 
                    cmp_econ_polar + cmp_cult_polar + 
                    Voter_Turnout + tv_it + 
                    v2x_polyarchy + gtm_parl +
                    coalition + decades +
                    (1 | country),
                  family = binomial(link='logit'),
                  data=reg_dat)

m.full.2 <- glmer(rb_ideol_brand ~ 
                    party_fam + past_pm + 
                    vote_share + party_age + 1 + 
                    cmp_econ_polar + cmp_cult_polar + 
                    Voter_Turnout + tv_it + 
                    v2x_polyarchy + gtm_parl +
                    coalition + decades +
                    (1 | country),
                  family = binomial(link='logit'),
                  data=reg_dat)

m.full.3 <- glmer(rb_org_brand ~ 
                    party_fam + past_pm + 
                    vote_share + party_age + 1 + 
                    cmp_econ_polar + cmp_cult_polar + 
                    Voter_Turnout + tv_it + 
                    v2x_polyarchy + gtm_parl +
                    coalition + decades +
                    (1 | country),
                  family = binomial(link='logit'),
                  data=reg_dat)

screenreg(l=list(m.full.1, m.full.2, m.full.3))

plot_dat <- rbind(margins_2ci(m.full.1), 
                  margins_2ci(m.full.2), 
                  margins_2ci(m.full.3))

```

## Table 1: Overall re-branding (1945-2023) - hierarchical logistic regression models

```{r, echo=T, message = T, include = T}

latex_table <- texreg(list(m.full.1, m.full.2, m.full.3),
       custom.model.names = c("party name", 
                              "nonparty name", 
                              "movement name"),
       custom.header = list("Classical" = 1, "Nonideological" = 2, "Nonideological"=3),
       doctype = FALSE, center = TRUE, dcolumn=TRUE, digits=2,
       use.packages=FALSE, booktabs = TRUE, float.pos = "h!", return.string = TRUE,
       single.row=TRUE, no.margin = TRUE,
       caption = "Overall re-branding (1945-2023) - hierarchical logistic regression models",
       caption.above = TRUE,
       label = "table:mlm_reg_table_all",
       include.loglik = FALSE, include.variance = FALSE,
       custom.coef.map = list("(Intercept)" = "Intercept",
                              "party_famRight-wing" = "Right-wing",
                              "party_famGreen/Ecologist" = "Green/Ecologist",
                              "party_famCommunist/Socialist" = "Communist/Socialist",
                              "party_famConservative" = "Conservative",
                              "party_famSocial democracy" = "Social democracy",
                              "party_famLiberal" = "Liberal",
                              "party_famAgrarian" = "Agrarian",
                              "party_famOther" = "Other",
                              "past_pm" = "Past PM (nr. of years)",
                              "party_age" = "Log(party age) average",
                              "vote_share" = "Vote share (average)",
                              "coalition" = "Coalition (nr. of years)",
                              "cmp_econ_polar" = "Econ. polariz. (average)",
                              "cmp_cult_polar" = "Cult. polariz. (average)",
                              "tv_it" = "Electoral volatil. (average)",
                              "Voter_Turnout" = "Turnout (average)",
                              "v2x_polyarchy" = "Electoral dem. (average)",
                              "gtm_parl" = "Presidentialism (average)",
                              "decades1970-1989" = "1970-1989",
                              "decades1990-2008" = "1990-2008",
                              "decades2009-2023" = "2009-2023"),
       groups = list("Party family (ref: Christ. dem.)"=2:9,
                     "Party features"=10:13,
                     "System features"=14:19,
                     "Decades (ref: 1945-1969)"=20:22),
       custom.gof.names	= c(NA, NA, NA, "Countries"))
       # file = paste0(path, "Appendix/", month, "/Tables/", "mlm_logits.tex"))
# Remove the offending \midrule.
# (Adjust the pattern if needed to precisely target the unwanted line.)
latex_table <- gsub("(?m)^\\\\cmidrule.*\n", "", latex_table, perl = TRUE)

# Write the modified LaTeX code to file.
writeLines(latex_table, con = "appendix/tables/mlm_overall_rebrand.tex")


```

## Figure 4: Logistic regression model of parties overall re-branding

```{r, echo=T, message = T, include = T}


plot_dat <- plot_dat %>% 
  rename(estimate=AME,
         term=factor) %>% 
  filter(!(grepl("(Intercept)", term))) %>% 
  mutate(DV=case_when(model %in% c("m.full.1") ~ "Typology rebrand",
                      model %in% c("m.full.2") ~ "Ideological rebrand",
                      model %in% c("m.full.3") ~ "Organizational rebrand")) %>% 
  mutate(DV=factor(DV, levels = c("Typology rebrand", 
                              "Ideological rebrand", 
                              "Organizational rebrand"))) %>% 
  mutate(DV=fct_rev(DV)) %>% 
  filter(term!="(Intercept)") %>% 
  mutate(term=case_when(
    term=="party_famAgrarian" ~ "Agrarian",
    term=="party_famCommunist/Socialist" ~ "Communist/Socialist",
    term=="party_famConservative" ~ "Conservative",
    term=="party_famGreen/Ecologist" ~ "Green/Ecologist",
    term=="party_famLiberal" ~ "Liberal",
    term=="party_famOther" ~ "Other",
    term=="party_famRight-wing" ~ "Right-wing",
    term=="party_famSocial democracy" ~ "Social democracy", 
    term=="past_pm" ~ "Past PM party",
    term=="opp_party" ~ "Opp. party",
    term=="party_age" ~ "Log(party age)",
    term=="vote_share" ~ "Vote share",
    term=="coalition" ~ "Electoral coalition",
    term=="Voter_Turnout" ~ "Turnout",
    term=="cmp_econ_polar" ~ "Econ. polariz.",
    term=="cmp_cult_polar" ~ "Cult. polariz.",
    term=="tv_it" ~ "Electoral volatil.",
    term=="v2x_polyarchy" ~ "Electoral dem.",
    term== "gtm_parl" ~ "Presidentialism",
    term=="decades1970-1989" ~ "1970-1989",
    term=="decades1990-2008" ~ "1990-2008",
    term=="decades2009-2023" ~ "2009-2023"
  )) %>% 
  mutate(term=factor(term, levels = c("Right-wing", "Green/Ecologist", "Communist/Socialist", 
                                      "Conservative", "Social democracy",
                                      "Liberal", "Agrarian", "Other", 
                                      "Past PM party", "Log(party age)", "Opp. party",
                                      "Vote share", "Electoral coalition", 
                                      "Econ. polariz.", "Cult. polariz.",
                                      "Electoral volatil.", "Turnout", 
                                      "Electoral dem.", "Presidentialism",
                                      "1970-1989", "1990-2008", "2009-2023"))) %>% 
  mutate(term=fct_rev(term)) %>%
  # mutate_at(vars(estimate, `2.5 %`, `97.5 %`, `5 %`, `95 %`), ~exp(.)) %>%
  mutate(facets_var=case_when(term %in% c("Liberal", 
                                      "Social democracy", "Communist/Socialist", 
                                      "Green/Ecologist", "Conservative", 
                                      "Right-wing", "Agrarian", 
                                      "Other") ~ "Party family (ref: Christian democracy)", 
                          term %in% c("Past PM party", "Opp. party", "Log(party age)", 
                                      "Vote share", "Electoral coalition") ~ "Party features",
                          term %in% c("Turnout",  "Econ. polariz.", 
                                      "Cult. polariz.", "Electoral volatil.",
                                      "Electoral dem.", "Presidentialism") ~ "System features",
                          term %in% c("1970-1989", "1990-2008", 
                                      "2009-2023") ~ "Decades (ref: 1945-1969)")) %>% 
  mutate(facets_var=factor(facets_var, levels = c("Party family (ref: Christian democracy)",
                                          "Party features", "System features",
                                          "Decades (ref: 1945-1969)"))) %>% 
  select(DV, term, estimate, facets_var, `2.5 %`, `97.5 %`, `5 %`, `95 %`) 

GeomPointrange$draw_key <-  function (data, params, size)     {
  
  draw_key_vpath <- function (data, params, size) {
    # only need to change the x&y coords so that the line is horizontal
    # originally, the vertical line was `0.5, 0.1, 0.5, 0.9`
    segmentsGrob(0.1, 0.5, 0.9, 0.5, 
                 gp = gpar(col = alpha(data$colour, data$alpha), 
                           lwd = data$size * .pt, lty = data$linetype, 
                           lineend = "butt"), arrow = params$arrow)
  }
  
  grid::grobTree(draw_key_vpath(data, params, size), 
                 draw_key_point(transform(data, size = data$size * 4), params))
}


space_between_bars <- 0.7

ggplot(plot_dat, aes(y=term, color=DV)) +
  geom_vline(xintercept = 0, linetype="dashed", color="gray60") +
  geom_point(aes(x=estimate, shape=DV), position=position_dodge(width=space_between_bars), size=2) +
  geom_linerange(aes(xmin=`2.5 %`, xmax=`97.5 %`,
  group=DV), size=0.5, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  geom_linerange(aes(xmin=`5 %`, xmax=`95 %`,
  group=DV), size=1.1, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  xlab("Average Marginal Effect (Response Scale)") +
  facet_wrap(~facets_var, ncol=2, scales = "free_y") + #
  scale_color_manual(name="", values=colors[1:3], guide=guide_legend(reverse = TRUE, nrow=1, byrow=TRUE)) +
  scale_shape_discrete(name="", guide=guide_legend(reverse = TRUE, nrow=1, byrow=TRUE)) +
  scale_y_discrete(labels = function(y) stringr::str_wrap(y, width = 15)) +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(1,"cm"),
        axis.title.y = element_blank(),
        axis.text.y = element_text(hjust=0.5))

ggsave(plot=last_plot(),
       filename="appendix/figures/coefs_mlm_overall_rebrand.eps",
       width=14.5,
       height=14.5,
       scale=1.2,
       dpi=400,
       units="cm")


```


```{r, echo=T, message = T, include = T}

  
m.full.1 <- glmer(rb_ideological_party ~
                    party_fam + past_pm + 
                    vote_share + party_age + 1 + 
                    cmp_econ_polar + cmp_cult_polar + 
                    Voter_Turnout + tv_it + 
                    v2x_polyarchy + gtm_parl +
                    coalition + decades +
                    (1 | country),
                  family = binomial(link='logit'),
                  data=reg_dat)

m.full.2 <- glmer(rb_nonideological_nonparty ~ 
                    party_fam + past_pm + 
                    vote_share + party_age + 1 + 
                    cmp_econ_polar + cmp_cult_polar + 
                    Voter_Turnout + tv_it + 
                    v2x_polyarchy + gtm_parl +
                    coalition + decades +
                    (1 | country),
                  family = binomial(link='logit'),
                  data=reg_dat)

m.full.3 <- glmer(rb_nonideological_movement ~ 
                    party_fam + past_pm + 
                    vote_share + party_age + 1 + 
                    cmp_econ_polar + cmp_cult_polar + 
                    Voter_Turnout + tv_it + 
                    v2x_polyarchy + gtm_parl +
                    coalition + decades +
                    (1 | country),
                  family = binomial(link='logit'),
                  data=reg_dat)

screenreg(l=list(m.full.1, m.full.2, m.full.3))

plot_dat <- rbind(margins_2ci(m.full.1), 
                  margins_2ci(m.full.2), 
                  margins_2ci(m.full.3))

```

## Table 2: Re-branding as specific types (1945-2023) - hierarchical logistic regression models


```{r, echo=T, message = T, include = T}

latex_table <- texreg(list(m.full.1, m.full.2, m.full.3),
       custom.model.names = c("party name", 
                              "nonparty name", 
                              "movement name"),
       custom.header = list("Classical" = 1, "Nonideological" = 2, "Nonideological"=3),
       doctype = FALSE, center = TRUE, dcolumn=TRUE, digits=2,
       use.packages=FALSE, booktabs = TRUE, float.pos = "h!", return.string = TRUE,
       single.row=TRUE, no.margin = TRUE,
       caption = "Re-branding as specific types (1945-2023) - hierarchical logistic regression models",
       caption.above = TRUE,
       label = "table:mlm_reg_table_all",
       include.loglik = FALSE, include.variance = FALSE,
       custom.coef.map = list("(Intercept)" = "Intercept",
                              "party_famRight-wing" = "Right-wing",
                              "party_famGreen/Ecologist" = "Green/Ecologist",
                              "party_famCommunist/Socialist" = "Communist/Socialist",
                              "party_famConservative" = "Conservative",
                              "party_famSocial democracy" = "Social democracy",
                              "party_famLiberal" = "Liberal",
                              "party_famAgrarian" = "Agrarian",
                              "party_famOther" = "Other",
                              "past_pm" = "Past PM (nr. of years)",
                              "party_age" = "Log(party age) average",
                              "vote_share" = "Vote share (average)",
                              "coalition" = "Coalition (nr. of years)",
                              "cmp_econ_polar" = "Econ. polariz. (average)",
                              "cmp_cult_polar" = "Cult. polariz. (average)",
                              "tv_it" = "Electoral volatil. (average)",
                              "Voter_Turnout" = "Turnout (average)",
                              "v2x_polyarchy" = "Electoral dem. (average)",
                              "gtm_parl" = "Presidentialism (average)",
                              "decades1970-1989" = "1970-1989",
                              "decades1990-2008" = "1990-2008",
                              "decades2009-2023" = "2009-2023"),
       groups = list("Party family (ref: Christ. dem.)"=2:9,
                     "Party features"=10:13,
                     "System features"=14:19,
                     "Decades (ref: 1945-1969)"=20:22),
       custom.gof.names	= c(NA, NA, NA, "Countries"))

# Remove the offending \midrule.
# (Adjust the pattern if needed to precisely target the unwanted line.)
latex_table <- gsub("(?m)^\\\\cmidrule.*\n", "", latex_table, perl = TRUE)

# Write the modified LaTeX code to file.
writeLines(latex_table, con = "appendix/tables/mlm_by_type_rebrand.tex")


```

## Figure 5: Logistic regression model of parties re-branding as specific types

```{r, echo=T, message = T, include = T}

plot_dat <- plot_dat %>% 
  rename(estimate=AME,
         term=factor) %>% 
  filter(!(grepl("(Intercept)", term))) %>% 
  mutate(DV=case_when(model %in% c("m.full.1") ~ "Classical\nparty name",
                      model %in% c("m.full.2") ~ "Nonideological\nnonparty name",
                      model %in% c("m.full.3") ~ "Nonideological\nmovement name")) %>% 
  mutate(DV=factor(DV, levels = c("Classical\nparty name",
                              "Nonideological\nnonparty name",
                              "Nonideological\nmovement name"))) %>% 
  mutate(DV=fct_rev(DV)) %>% 
  filter(term!="(Intercept)") %>% 
  mutate(term=case_when(
    term=="party_famAgrarian" ~ "Agrarian",
    term=="party_famCommunist/Socialist" ~ "Communist/Socialist",
    term=="party_famConservative" ~ "Conservative",
    term=="party_famGreen/Ecologist" ~ "Green/Ecologist",
    term=="party_famLiberal" ~ "Liberal",
    term=="party_famOther" ~ "Other",
    term=="party_famRight-wing" ~ "Right-wing",
    term=="party_famSocial democracy" ~ "Social democracy", 
    term=="past_pm" ~ "Past PM party",
    term=="opp_party" ~ "Opp. party",
    term=="party_age" ~ "Log(party age)",
    term=="vote_share" ~ "Vote share",
    term=="coalition" ~ "Electoral coalition",
    term=="Voter_Turnout" ~ "Turnout",
    term=="cmp_econ_polar" ~ "Econ. polariz.",
    term=="cmp_cult_polar" ~ "Cult. polariz.",
    term=="tv_it" ~ "Electoral volatil.",
    term=="v2x_polyarchy" ~ "Electoral dem.",
    term== "gtm_parl" ~ "Presidentialism",
    term=="decades1970-1989" ~ "1970-1989",
    term=="decades1990-2008" ~ "1990-2008",
    term=="decades2009-2023" ~ "2009-2023"
  )) %>% 
  mutate(term=factor(term, levels = c("Right-wing", "Green/Ecologist", "Communist/Socialist", 
                                      "Conservative", "Social democracy",
                                      "Liberal", "Agrarian", "Other", 
                                      "Past PM party", "Log(party age)", "Opp. party",
                                      "Vote share", "Electoral coalition", 
                                      "Econ. polariz.", "Cult. polariz.",
                                      "Electoral volatil.", "Turnout", 
                                      "Electoral dem.", "Presidentialism",
                                      "1970-1989", "1990-2008", "2009-2023"))) %>% 
  mutate(term=fct_rev(term)) %>%
  mutate(facets_var=case_when(term %in% c("Liberal", 
                                      "Social democracy", "Communist/Socialist", 
                                      "Green/Ecologist", "Conservative", 
                                      "Right-wing", "Agrarian", 
                                      "Other") ~ "Party family (ref: Christian democracy)", 
                          term %in% c("Past PM party", "Opp. party", "Log(party age)", 
                                      "Vote share", "Electoral coalition") ~ "Party features",
                          term %in% c("Turnout",  "Econ. polariz.", 
                                      "Cult. polariz.", "Electoral volatil.",
                                      "Electoral dem.", "Presidentialism") ~ "System features",
                          term %in% c("1970-1989", "1990-2008", 
                                      "2009-2023") ~ "Decades (ref: 1945-1969)")) %>% 
  mutate(facets_var=factor(facets_var, levels = c("Party family (ref: Christian democracy)",
                                          "Party features", "System features",
                                          "Decades (ref: 1945-1969)"))) %>% 
  select(DV, term, estimate, facets_var, `2.5 %`, `97.5 %`, `5 %`, `95 %`) 

GeomPointrange$draw_key <-  function (data, params, size)     {
  
  draw_key_vpath <- function (data, params, size) {
    segmentsGrob(0.1, 0.5, 0.9, 0.5, 
                 gp = gpar(col = alpha(data$colour, data$alpha), 
                           lwd = data$size * .pt, lty = data$linetype, 
                           lineend = "butt"), arrow = params$arrow)
  }
  
  grid::grobTree(draw_key_vpath(data, params, size), 
                 draw_key_point(transform(data, size = data$size * 4), params))
}


space_between_bars <- 0.7

ggplot(plot_dat, aes(y=term, color=DV)) +
  geom_vline(xintercept = 0, linetype="dashed", color="gray60") +
  geom_point(aes(x=estimate, shape=DV), position=position_dodge(width=space_between_bars), size=2) +
  geom_linerange(aes(xmin=`2.5 %`, xmax=`97.5 %`,
  group=DV), size=0.5, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  geom_linerange(aes(xmin=`5 %`, xmax=`95 %`,
  group=DV), size=1.1, position=position_dodge(width=space_between_bars), key_glyph = "path") +
  xlab("Average Marginal Effect (Response Scale)") +
  facet_wrap(~facets_var, ncol=2, scales = "free_y") + #
  scale_color_manual(name="", values=c("#0072B2", "#56B4E9", "#D55E00"), guide=guide_legend(reverse = TRUE, nrow=1, byrow=TRUE)) +
  scale_shape_discrete(name="", guide=guide_legend(reverse = TRUE, nrow=1, byrow=TRUE)) +
  scale_y_discrete(labels = function(y) stringr::str_wrap(y, width = 15)) +
  theme_linedraw() +
  theme(legend.title=element_blank(), 
        legend.position="bottom",
        legend.key.width = unit(2,"cm"),
        axis.title.y = element_blank(),
        axis.text.y = element_text(hjust=0.5))

ggsave(plot=last_plot(),
       filename="appendix/figures/coefs_mlm_types_rebrand.eps",
       width=14.5,
       height=14.5,
       scale=1.2,
       dpi=400,
       units="cm")


```



```{r, echo=T, message = T, include = T}

```